<template>
  <view class="property-contact">
    <!-- 物业联系方式 -->
    <view class="contact-card">
      <view class="section-title">物业联系方式</view>
      <view class="contact-list">
        <view class="contact-item">
          <text class="contact-label">物业热线</text>
          <text class="contact-value">400-888-9999</text>
          <view class="call-button" @tap="makeCall('400-888-9999')">拨打</view>
        </view>
        <view class="contact-item">
          <text class="contact-label">紧急维修</text>
          <text class="contact-value">0755-12345678</text>
          <view class="call-button" @tap="makeCall('0755-12345678')">拨打</view>
        </view>
        <view class="contact-item">
          <text class="contact-label">投诉建议</text>
          <text class="contact-value">0755-87654321</text>
          <view class="call-button" @tap="makeCall('0755-87654321')">拨打</view>
        </view>
        <view class="contact-item">
          <text class="contact-label">服务时间</text>
          <text class="contact-value">周一至周日 08:00-22:00</text>
        </view>
      </view>
    </view>
    
    <!-- 在线留言 -->
    <view class="message-form">
      <view class="section-title">在线留言</view>
      
      <!-- 留言类型选择 -->
      <view class="message-type">
        <view 
          v-for="type in messageTypes" 
          :key="type.value"
          :class="['type-item', selectedType === type.value ? 'active' : '']"
          @tap="selectType(type.value)"
        >
          <text>{{ type.label }}</text>
        </view>
      </view>
      
      <!-- 留言内容 -->
      <view class="message-content">
        <textarea 
          class="content-input" 
          placeholder="请输入您的留言内容，我们会尽快回复" 
          v-model="messageContent"
          maxlength="500"
        ></textarea>
        <view class="word-count">{{ messageContent.length }}/500</view>
      </view>
      
      <!-- 图片上传 -->
      <view class="message-images">
        <view class="upload-title">相关图片（选填）</view>
        <view class="image-upload">
          <view 
            class="image-item" 
            v-for="(image, index) in images" 
            :key="index"
          >
            <image :src="image" mode="aspectFill"></image>
            <view class="delete-icon" @tap="deleteImage(index)">×</view>
          </view>
          <view class="upload-button" @tap="chooseImage" v-if="images.length < 3">
            <text class="plus">+</text>
            <text class="upload-text">上传图片</text>
          </view>
        </view>
        <view class="upload-tip">最多上传3张图片，每张不超过5MB</view>
      </view>
      
      <!-- 联系方式 -->
      <view class="contact-info">
        <view class="input-item">
          <text class="label">联系人</text>
          <input type="text" v-model="contactName" placeholder="请输入联系人姓名" />
        </view>
        <view class="input-item">
          <text class="label">手机号码</text>
          <input type="number" v-model="contactPhone" placeholder="请输入联系电话" maxlength="11" />
        </view>
      </view>
      
      <!-- 提交按钮 -->
      <view class="button-group">
        <button 
          class="submit-button" 
          @tap="submitMessage" 
          :disabled="!isFormValid"
        >
          提交留言
        </button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      messageTypes: [
        { value: 'suggestion', label: '建议反馈' },
        { value: 'complaint', label: '投诉' },
        { value: 'repair', label: '报修' },
        { value: 'inquiry', label: '咨询' },
        { value: 'other', label: '其他' }
      ],
      selectedType: '',
      messageContent: '',
      images: [],
      contactName: '',
      contactPhone: '',
      loading: false
    }
  },
  computed: {
    isFormValid() {
      return this.selectedType && 
             this.messageContent && 
             this.contactName && 
             this.contactPhone
    }
  },
  onLoad() {
    // 获取用户信息，自动填充联系方式
    this.getUserInfo()
  },
  methods: {
    selectType(type) {
      this.selectedType = type
    },
    makeCall(phoneNumber) {
      uni.makePhoneCall({
        phoneNumber: phoneNumber,
        fail: () => {
          uni.showToast({
            title: '拨打电话失败',
            icon: 'none'
          })
        }
      })
    },
    chooseImage() {
      uni.chooseImage({
        count: 3 - this.images.length,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          // 检查图片大小
          const validImages = res.tempFilePaths.filter((path, index) => {
            return res.tempFiles[index].size <= 5 * 1024 * 1024 // 5MB
          })
          
          if (validImages.length < res.tempFilePaths.length) {
            uni.showToast({
              title: '部分图片超过5MB，已过滤',
              icon: 'none'
            })
          }
          
          this.images = [...this.images, ...validImages]
        }
      })
    },
    deleteImage(index) {
      this.images.splice(index, 1)
    },
    getUserInfo() {
      try {
        const userInfo = uni.getStorageSync('userInfo')
        if (userInfo) {
          const user = JSON.parse(userInfo)
          this.contactName = user.name || ''
          this.contactPhone = user.phone || ''
        }
      } catch (e) {
        console.error('获取用户信息失败', e)
      }
    },
    async submitMessage() {
      if (this.loading) return
      this.loading = true
      
      try {
        // 先上传图片
        const uploadedImages = await this.uploadImages()
        
        // 提交留言
        const res = await this.$api.submitPropertyMessage({
          type: this.selectedType,
          content: this.messageContent,
          images: uploadedImages,
          contactName: this.contactName,
          contactPhone: this.contactPhone
        })
        
        uni.showToast({
          title: '提交成功',
          icon: 'success'
        })
        
        // 延迟返回上一页
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } catch (error) {
        console.error('提交留言失败', error)
        uni.showToast({
          title: '提交失败，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    async uploadImages() {
      if (this.images.length === 0) return []
      
      const uploadPromises = this.images.map(image => {
        return new Promise((resolve, reject) => {
          uni.uploadFile({
            url: this.$api.baseUrl + '/upload',
            filePath: image,
            name: 'file',
            success: (res) => {
              const data = JSON.parse(res.data)
              resolve(data.url)
            },
            fail: (err) => {
              reject(err)
            }
          })
        })
      })
      
      try {
        return await Promise.all(uploadPromises)
      } catch (error) {
        console.error('上传图片失败', error)
        throw new Error('上传图片失败')
      }
    }
  }
}
</script>

<style lang="scss">
.property-contact {
  padding: 20rpx;
  background: #f5f5f5;
  min-height: 100vh;
}

.contact-card, .message-form {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(106, 17, 203, 0.1);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 30rpx;
  color: #333;
  position: relative;
  padding-left: 20rpx;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 6rpx;
  width: 8rpx;
  height: 30rpx;
  background: #6a11cb;
  border-radius: 4rpx;
}

/* 联系方式卡片样式 */
.contact-list {
  margin-top: 20rpx;
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1px solid #f0f0f0;
}

.contact-item:last-child {
  border-bottom: none;
}

.contact-label {
  width: 160rpx;
  color: #666;
  font-size: 28rpx;
}

.contact-value {
  flex: 1;
  color: #333;
  font-size: 28rpx;
}

.call-button {
  width: 100rpx;
  height: 50rpx;
  line-height: 50rpx;
  text-align: center;
  background: #6a11cb;
  color: #fff;
  font-size: 24rpx;
  border-radius: 25rpx;
}

/* 留言表单样式 */
.message-type {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 30rpx;
}

.type-item {
  padding: 15rpx 30rpx;
  background: #f5f5f5;
  border-radius: 30rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
  font-size: 26rpx;
  color: #666;
}

.type-item.active {
  background: #6a11cb;
  color: #fff;
}

.message-content {
  position: relative;
  margin-bottom: 30rpx;
}

.content-input {
  width: 100%;
  height: 200rpx;
  background: #f5f5f5;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

.word-count {
  position: absolute;
  right: 20rpx;
  bottom: 20rpx;
  font-size: 24rpx;
  color: #999;
}

.message-images {
  margin-bottom: 30rpx;
}

.upload-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.image-upload {
  display: flex;
  flex-wrap: wrap;
}

.image-item {
  width: 160rpx;
  height: 160rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
  position: relative;
  border-radius: 8rpx;
  overflow: hidden;
}

.image-item image {
  width: 100%;
  height: 100%;
}

.delete-icon {
  position: absolute;
  top: 0;
  right: 0;
  width: 40rpx;
  height: 40rpx;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  text-align: center;
  line-height: 36rpx;
  font-size: 32rpx;
  border-radius: 0 0 0 8rpx;
}

.upload-button {
  width: 160rpx;
  height: 160rpx;
  background: #f5f5f5;
  border-radius: 8rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.plus {
  font-size: 50rpx;
  color: #999;
  margin-bottom: 10rpx;
}

.upload-text {
  font-size: 24rpx;
  color: #999;
}

.upload-tip {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.contact-info {
  margin-bottom: 30rpx;
}

.input-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.label {
  width: 160rpx;
  font-size: 28rpx;
  color: #333;
}

.input-item input {
  flex: 1;
  height: 80rpx;
  background: #f5f5f5;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
}

.button-group {
  margin-top: 40rpx;
}

.submit-button {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background: linear-gradient(135deg, #6a11cb 0%, #8e44ad 100%);
  color: #fff !important;
  border-radius: 45rpx;
  text-align: center;
  font-size: 32rpx;
  font-weight: bold;
  letter-spacing: 2rpx;
  box-shadow: 0 8rpx 20rpx rgba(106, 17, 203, 0.3);
  
  &:disabled {
    background: #cccccc;
    box-shadow: none;
  }
}
</style>